<?php
class User extends Node {
    private $user_id = 0;
    private $username = '';
    private $error = '';


    public function init() {
        $this->action_access = array(
            'login' => ACTION_ACCESS_PUBLIC
        );
    }
    
    
    public function logined() {
        $this->_login();
        return ($this->user_id > 0);
    }


    /* --- Actions --- */
    public function act_login() {
        if ( ! $this->_login()) {
            $out = out();
            $out->add_title('User Login');
            $data = array(
                'error' => $this->error,
                'username' => $this->username
            );
            $out->add_block(tos_view('user/login', $data));
        } else {
            tos_redirect();
        }
    }
    
    
    public function act_logout() {
        if (isset($_SESSION)) {
            unset($_SESSION['user_id']);
            session_destroy();
        }
        tos_redirect();
    }

    /* --- end Actions --- */

    /* --- Private Funcion --- */
    private function _login() {
        if ($this->user_id <= 0) {
            if ( ! isset($_SESSION)) session_start();
            if ( ! isset($_SESSION['user_id'])) {
                if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] == 'POST') {
                    $username = tos_http_post('username');
                    $password = tos_http_post('password');
                    $this->username = $username;
                    if ($user_id = $this->model('user')->authenticate($username, $password)) {
                        $_SESSION['user_id'] = $user_id;
                    } else {
                        $this->error = 'Username or password is not right !';
                    }
                }
            }
            if (isset($_SESSION['user_id']) && $user_id = (int)$_SESSION['user_id']) {
                $this->user_id = $user_id;
            }
        }
        return $this->user_id;
    }
    /* --- End Private Function --- */
}
?>